package http

import (
	"fmt"
	"go-monitor/common/model"
	"go-monitor/common/utility"
	"go-monitor/server/g"
	"go-monitor/server/service"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/toolkits/file"
)

func configCommonRoutes() {
	http.HandleFunc("/update", update)
	http.HandleFunc("/test", test)
}

// update Agent更新程序
func update(resp http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	if len(req.Form["v"]) > 0 {
		agentVersion := req.Form["v"][0]
		if agentVersion != g.Config().AgentVersion {
			path := file.SelfDir() + "/update/agent"
			buff, err := ioutil.ReadFile(path)
			if err != nil {
				g.Logger.Error("更新agent异常:", err)
			}
			resp.Write(buff)
			return
		}
		resp.WriteHeader(204)
		return
	}
}

// test 测试程序
func test(resp http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	// 验证签名
	commonsign := model.CommonSign{}
	commonsign.Diytime = utility.GetDiyFormatNowHour()
	commonsign.Sign = r.Form["sign"][0]
	if !CheckCommonSign(commonsign) {
		log.Println("test sign error")
		g.Logger.Error("test sign error")
		return
	}

	ip := "127.0.0.1"
	// rpc请求客户端
	var client = &g.SingleConnRpcClient{}
	client.RpcServer = ip + g.Config().RPCClient.Addr
	client.Timeout = time.Duration(g.Config().RPCClient.Timeout) * time.Second
	// rpc请求参数
	req := model.NullRPCRequest{}
	agentPublicKey, _ := getAgentPublicKey(ip)
	sign, _ := service.RsaEncrypt([]byte(model.SignOrign), agentPublicKey)
	req.Sign = sign

	err := client.Call("Client.Test", req, &resp)
	if err != nil {
		log.Println("test error", err)
		g.Logger.Error("Test error", err)
	}
	fmt.Println(resp)
	return
}
